package com.etc.nacosdiscovery.filter;


import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@Slf4j
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("custom global filter");

        ServerHttpRequest request = exchange.getRequest();
        //通过ServerWebExchange得到请求有关数据
        RequestPath path =request.getPath();
        log.info("path "+path);
        //得到 请求头
        HttpHeaders headers = request.getHeaders();
        //得到 getQueryParams
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //得到 第一个参数 (别误会)
        String token = request.getQueryParams().getFirst("token");
        if (StringUtil.isNullOrEmpty(token)) {
            //如果没有传递token,禁止访问
            log.info("无token，鉴权失败!");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束
            return exchange.getResponse().setComplete();
        }
        //过滤器链的继续执行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}

